#!/bin/bash
# date: 2022/11/23
# auth: fearless11
# desc: install consul
# https://learn.hashicorp.com/tutorials/consul/deployment-guide
# https://mp.weixin.qq.com/s/yPyTWvMlia7YknMXdrsOXA

ip_local=$(/usr/sbin/ip add | grep inet | grep global | grep -Ev 'docker' | awk '{print $2}' | awk -F/ '{print $1}' | tail -1)
ip_local=127.0.0.1
port=8500
addr=${ip_local}:${port}
docker_name="consul_${port}"
image="consul:1.18.1"
image="m.daocloud.io/docker.io/bitnami/consul:1.18.1"

# Error response from daemon: unknown log opt 'max-size' for journald log driver.
# grep log-driver /etc/sysconfig/docker
# 修改前 OPTIONS='--selinux-enabled --log-driver=journald --signature-verification=false'
# 修改后 OPTIONS='--selinux-enabled --log-driver=json-file --signature-verification=false'

docker_start_dev() {
  docker run -d \
    --name ${docker_name} \
    -m 800m \
    --net=host \
    --restart=always \
    --log-opt max-size=100m \
    --log-opt max-file=10 \
    ${image} \
    consul \
    agent \
    -dev
}

docker_stop() {
  docker stop ${docker_name}
  docker rm ${docker_name}
}

docker_exec() {
  docker exec -it ${docker_name} sh
}

docker_logs() {
  docker logs --tail=10 ${docker_name}
}

query_datacenter() {
  curl -s http://${addr}/v1/catalog/datacenters
}

query_nodes() {
  curl -s http://${addr}/v1/catalog/nodes | python -m json.tool
}

query_service() {
  curl -s http://${addr}/v1/agent/services
}

test_register() {
  curl --request PUT \
    --url http://${addr}/v1/agent/service/register \
    --header 'content-type: "application/json"' \
    --data '{
    "id": "test-127.0.0.1",
    "name": "node_exporter",
    "tags": ["test"],
    "meta": {
         "env": "test",
         "biz": "vvv"
    },
    "address": "127.0.0.1",
    "port": 8500,
    "checks": [
        {
            "http": "http://127.0.0.1:8500",
            "interval": "35s"
        }
    ]
   }'
}

test_deregister() {
  curl -XPUT "http://${addr}/v1/agent/service/deregister/test-127.0.0.1"
}

case $1 in
start)
  docker_start_dev
  ;;
stop)
  docker_stop
  ;;
exec)
  docker_exec
  ;;
logs)
  docker_logs
  ;;
datacenter)
  query_datacenter
  ;;
nodes)
  query_nodes
  ;;
service)
  query_service
  ;;
register)
  test_register
  ;;
deregister)
  test_deregister
  ;;
*)
  echo "$0 start|stop|exec|logs|datacenter|nodes|service|register|deregister"
  ;;
esac
